package evolution;

import hypergraph.HyperEdge;
import hypergraph.HyperGraph;
import hypergraph.Node;
import hypergraph.RuleSet;

import java.util.ArrayList;

import org.jgap.IChromosome;
import org.jgap.impl.CompositeGene;


import bangor.aiia.jge.population.InvalidPhenotypeException;



public class GraphMapper {
	public  HyperGraph map(IChromosome chrom){
		HyperGraph g = new HyperGraph();
		ArrayList<Node> nodes = new ArrayList<Node>();
		nodes.add(new Node());
		nodes.add(new Node());
		
		g.addVertex(nodes.get(0));
		g.addVertex(nodes.get(1));
		HyperEdge e1 = new HyperEdge('A');
		g.addEdge(e1,nodes.subList(0, 2));
		RuleSet rules;
		try {
			rules = new RuleSet(new CodonString((CompositeGene)chrom.getGene(0), 1));
		} catch (InvalidPhenotypeException e2) {
			System.out.println("invalid hg grammar");
			rules = null;
		}
		//
		//System.out.println("rulesset created");
		CodonString gCodons = new CodonString((CompositeGene)chrom.getGene(1), 5);
		boolean replacing = true;
		int k = 0;
		while(replacing && rules != null){
			ArrayList<HyperEdge> toReplace = g.listNonTerminals();
			//System.out.println("to replace size " + toReplace.size());
			if(toReplace.size() <= 0)
				replacing = false;
			for(HyperEdge r : toReplace){
				try {
					g.replace(r, rules.getGraph(r.getLabel(), gCodons.next()).clone());
				} catch (InvalidPhenotypeException e) {
					replacing = false;
				}
				k++;
			}
		}
		return g;
	}
}
